<template>
  <div>
    <!-- <div v-if="!isFlow" class="form-header">
      <el-button @click="handleCacel">取消</el-button>
      <el-button v-if="Number(formData.status) > 1" @click="handleFlowRecord">
        <svg-icon icon-class="liuzhuanjilu" />
        流转记录
      </el-button>
      <el-button
        v-if="(Number(formData.status) === 1 || !formData?.status) && !formData?.applyStatus"
        :disabled="disabled"
        @click="handleSubmit('1')">
        保存为草稿
      </el-button>
      <el-button
        v-if="(Number(formData.status) === 1 || !formData?.status) && !formData?.applyStatus"
        :disabled="disabled"
        type="primary"
        @click="handleSubmit('2')">
        提交
      </el-button>
    </div> -->
    <div class="page">
      <DynamicForm
        ref="queryRef"
        v-model="formData"
        :disabled="disabled || isFlow"
        :config="formConfig"
        :items="formItems"
        :inline="true"
        :dict-data="{ case_source, work_status }"></DynamicForm>
      <div class="table-toolbar">
        <div class="left">
          <span class="form-title-text">现场检查</span>
        </div>
        <div class="right"></div>
      </div>
      <div v-if="!disabled">
        <label class="el-form-item__label" style="font-size: 14px">是否已经登记现场检查</label>
        <el-radio-group v-model="formData2.field16" :disabled="disabled || isFlow" class="ml-4" @change="getCheckList">
          <el-radio label="0" size="large">否</el-radio>
          <el-radio label="1" size="large">是</el-radio>
        </el-radio-group>
        <el-select
          v-show="formData2.field16 === '1'"
          v-model="checkCurrent"
          style="margin-left: 10px; width: 18vw"
          placeholder="请选择现场检查"
          @change="handleCheck">
          <el-option v-for="item in checkList" :key="item.id" :label="item.label" :value="item.id"></el-option>
        </el-select>
        <el-button :disabled="disabled || isFlow" style="float: right" @click="handleAdd">添加现场检查</el-button>
      </div>
      <Table :data="tableData" :columns="columnsDetail" border style="margin-bottom: 40px; margin-top: 10px">
        <template #checkDate="{ row }">
          {{ row.inspectionStartTime + ' ~ ' + row.inspectionEndTime }}
        </template>
        <template #location="{ row }">
          {{
            settings.cityName +
            settings.areaName +
            street_of_area.find(item => item.value === row.streetOfLocation)?.label +
            row.location
          }}
        </template>
        <template #action="{ row, $index }">
          <el-button link type="primary" @click="handleEdit(row, 'view')">查看</el-button>
          <el-button link type="primary" @click="handleExport(row)">导出</el-button>
          <el-button :disabled="disabled || isFlow" link type="primary" @click="handleEdit(row, 'edit')">
            编辑
          </el-button>
          <el-button :disabled="disabled || isFlow" link type="danger" @click="handleDelete(row, $index)">
            删除
          </el-button>
        </template>
      </Table>
      <DynamicForm
        ref="queryRef2"
        v-model="formData"
        :disabled="disabled"
        :config="formConfig"
        :items="formItemsTwo"
        :inline="true"
        :dict-data="{ case_source, work_status }">
        <template #partyId>
          <el-select
            v-model="formData.partyId"
            filterable
            remote
            clearable
            :disabled="disabled || isFlow"
            reserve-keyword
            placeholder="请输入当事人名称"
            :remote-method="handlepartySearch"
            :loading="partyLoading"
            style="width: calc(100% - 45px); margin-right: 6px"
            @change="handlepartyChange">
            <el-option v-for="item in partyOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-button link type="primary" :disabled="disabled || isFlow" @click="handlePartyAdd">添加</el-button>
        </template>
        <template #streetOfCompanyAddress>
          <el-row :gutter="20">
            <el-col :span="7">
              <el-input :value="settings.cityName" disabled placeholder="城市"></el-input>
            </el-col>
            <el-col :span="7">
              <el-input :value="settings.areaName" disabled placeholder="区县"></el-input>
            </el-col>
            <el-col :span="10">
              <el-select
                v-model="formData.streetOfCompanyAddress"
                disabled
                clearable
                filterable
                placeholder="请选择街道">
                <el-option
                  v-for="(item, index) in street_of_area"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </template>
        <template #address>
          <el-input v-model="formData.address" disabled placeholder="详细地址"></el-input>
        </template>
        <template #caseCause>
          <!-- 案由 -->
          <div style="position: relative">
            <el-input
              v-model="formData.caseCause"
              type="textarea"
              :rows="4"
              readonly
              placeholder="请选择案由"
              style="cursor: pointer"
              @click="showCausePicker = true" />
          </div>
        </template>
        <!-- 企业情况 -->
        <template #companyProfile>
          <SmartTextInput
            v-model="formData.companyProfile"
            type="textarea"
            :rows="4"
            placeholder="请输入企业情况，输入关键词后按Tab键快速补全"
            :min-length="2"
            :max-suggestions="5"
            contentType="4"
            @select="handleSuggestionSelect" />
        </template>
        <template #siteDescription>
          <!-- 检查情况 -->
          <SmartTextInput
            v-model="formData.siteDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入现场情况，输入关键词后按Tab键快速补全"
            :min-length="2"
            :max-suggestions="5"
            contentType="5"
            @select="handleSuggestionSelect" />
        </template>
        <template #caseIntroduction>
          <!-- 案情简介及立案理由 -->
          <!-- :articleDatabase="contentArticles" -->
          <SmartTextInput
            v-model="formData.caseIntroduction"
            type="textarea"
            :rows="4"
            placeholder="请输入案情简介及立案理由，输入关键词后按Tab键快速补全"
            :min-length="2"
            :max-suggestions="5"
            contentType="3"
            :preId="formData.caseCauseId"
            @select="handleSuggestionSelect" />
        </template>
        <template #handlerOpinion>
          <!-- 承办人意见 -->
          <!-- :articleDatabase="opinionArticles" -->
          <SmartTextInput
            v-model="formData.handlerOpinion"
            type="textarea"
            :rows="4"
            placeholder="请输入承办人意见，输入关键词后按Tab键快速补全"
            :min-length="2"
            :max-suggestions="5"
            :disabled="disabled || isFlow"
            contentType="2"
            @select="handleSuggestionSelect" />
        </template>
        <template #remarks>
          <!-- 备注 -->
          <!-- :articleDatabase="remarkArticles" -->
          <!-- <SmartTextInput
            v-model="formData.remarks"
            type="textarea"
            :rows="4"
            placeholder="请输入备注，输入关键词后按Tab键快速补全"
            :min-length="2"
            :max-suggestions="5"
            contentType="4"
            @select="handleSuggestionSelect" /> -->
          <el-input v-model="formData.remarks" type="textarea" :rows="4" placeholder="请输入备注" />
        </template>
        <template #inspectorId1>
          <el-select
            v-model="formData.inspectorId1"
            filterable
            clearable
            :disabled="disabled || isFlow"
            placeholder="请输入执法人员"
            style="width: calc(100% - 45px); margin-right: 6px"
            @change="handlepartyChange1">
            <el-option v-for="item in inspectorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>
        <template #inspectorId2>
          <el-select
            v-model="formData.inspectorId2"
            filterable
            clearable
            :disabled="disabled || isFlow"
            placeholder="请输入执法人员"
            style="width: calc(100% - 45px); margin-right: 6px"
            @change="handlepartyChange2">
            <el-option v-for="item in inspectorOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </template>
      </DynamicForm>
      <div v-if="!isFlow" class="form-footer">
        <el-button @click="handleCacel">取消</el-button>
        <el-button :loading="preViewLoading" @click="handlePreview">预览</el-button>
        <el-button v-if="Number(formData.status) > 1 && formData.caseProcedure !== '1'" @click="handleFlowRecord">
          <svg-icon icon-class="liuzhuanjilu" />
          流转记录
        </el-button>
        <el-button
          v-if="Number(formData.status) === 1 || !formData?.status"
          :disabled="disabled"
          @click="handleSubmit('1')">
          保存为草稿
        </el-button>
        <el-button
          v-if="Number(formData.status) === 1 || !formData?.status"
          :disabled="disabled"
          type="primary"
          @click="handleSubmit('2')">
          提交
        </el-button>
      </div>
      <!-- 添加当事人信息 -->
      <partyDetail v-model:value="partyOpen" title="添加当事人信息" @getList="setParty" />
      <!-- 现场检查 -->
      <Transcript
        v-model:modalvalue="checkModalVisible"
        v-if="checkModalVisible"
        :id="formData2.id"
        :checkBtnType="checkBtnType"
        :partyId="formData.partyId"
        @handleSave="handleSave" />
    </div>
    <!-- 案由选择弹窗 -->
    <el-dialog v-model="showCausePicker" title="选择案由" width="500px" :before-close="closeCausePicker">
      <el-select
        v-model="formData.caseCauseId"
        clearable
        filterable
        placeholder="请选择案由"
        style="width: 100%"
        @change="selectCaseCause">
        <el-option v-for="(item, index) in caseCauseList" :key="item.id" :label="item.content" :value="item.id" />
      </el-select>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeCausePicker">取消</el-button>
          <el-button type="primary" @click="confirmCaseCause">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 流转记录 -->
    <flow-record v-model:modelValue="circulationVisible" :flow-list="circulationList" />
  </div>
</template>

<script setup lang="ts">
import DynamicForm from '@/components/DynamicForm/index.vue'
import Table from '@/components/Table'
import SmartTextInput from '@/components/SmartTextInput/index.vue'
import { ref, getCurrentInstance, watch, onMounted, nextTick, onBeforeMount } from 'vue'
import { ElMessage } from 'element-plus'
import { useTableColumns } from './config'
import { useDeleteConfirm } from '@/hooks/useDeleteConfirm'
import partyDetail from '@/views/workbench/filingReview/party/detail.vue'
import { useRouter, useRoute } from 'vue-router'
import useUserStore from '@/store/modules/user'
import { listPartyinfo } from '@/api/partyinfo/index'
import Transcript from './transcript.vue'
import settings from '@/settings.js'
import { onSiteInspectionExport, onSiteInspectionDetail } from '@/api/onSiteInspection/index.js'
import {
  registrationcaseAdd,
  registrationcaseSubmit,
  registrationcaseDetail,
  registrationcaseUpdate,
  registrationcaseReview,
  registrationcasePreviewPdf,
  getUnboundSiteInspections,
} from '@/api/filingReview/register.js'
import { getUserEnforcementNo } from '@/api/system/user.js'
import { downloadBlob } from '@/utils/download.js'
import { commontermsGet } from '@/api/filingReview/register.js'
import { getTodoFlowRecord } from '@/api/workFlow/index'
import flowRecord from '@/components/flowRecord/index.vue'

const props = defineProps({
  isFlow: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()
const route = useRoute()
const { confirmDeleteSingle } = useDeleteConfirm()

const userStore = useUserStore()

const { proxy } = getCurrentInstance()
const { case_source, work_status, street_of_area } = proxy.useDict('case_source', 'work_status', 'street_of_area')
const formData = ref<any>({
  caseSource: undefined,
  businessType: undefined,
  inspectorId1: String(userStore.id),
  inspectorCertNo1: userStore.enforcementNo,
  streetOfCompanyAddress: undefined,
  address: undefined,
  inspectorId2: '',
})

// 案由选择相关变量
const showCausePicker = ref(false)

const disabled = route.query.type === 'view'

const {
  formConfigDetail: formConfig,
  formItemsDetail: formItems,
  columnsDetail,
  formItemsDetailTwo: formItemsTwo,
} = useTableColumns(props.isFlow, disabled)
// 获取详情
async function getDetail(id: string) {
  const res = await registrationcaseDetail(id)
  if (res.code === 200) {
    formData.value = res.data
    formData.value.inspectorId1 = String(formData.value.inspectorId1)
    formData.value.inspectorId2 = String(formData.value.inspectorId2)
    tableData.value = res.data.tSiteInspectionRecordList || []
  }
}

// 当事人搜索以及回显 start =========================================================
const partyLoading = ref(false)
const partyOptions = ref<Array<any>>([])
const handlepartySearch = async (query: string) => {
  partyLoading.value = true
  const res: any = await listPartyinfo({
    pageNum: 1,
    pageSize: 9999,
    partyName: query,
  })
  partyLoading.value = false
  partyOptions.value = res.rows.map(item => {
    return { value: String(item.id), label: item.partyName, ...item }
  })
}
handlepartySearch('')
// 添加当事人
const partyOpen = ref(false)
const handlePartyAdd = () => {
  partyOpen.value = true
}
// 新增后回调
const setParty = async (form: any) => {
  await handlepartySearch('')
  partyOptions.value.forEach(item => {
    if (item.label === form.partyName) {
      formData.value.partyId = item.value
    }
  })
  formData.value.partyName = form.partyName
  formData.value.streetOfCompanyAddress = form.streetOfCompanyAddress
  formData.value.address = form.address
  formData.value.postalCode = form.postalCode
  formData.value.unifiedSocialCreditCode = form.unifiedSocialCreditCode
  formData.value.businessType = form.businessType
  formData.value.contactPhone = form.phone
  formData.value.legalRepresentative = form.legalRepresentative
  formData.value.position = form.onsitePosition
}
// 选择当事人
const handlepartyChange = (val: string) => {
  if (val) {
    partyOptions.value.forEach(item => {
      if (item.value === val) {
        formData.value.postalCode = item.postalCode
        formData.value.unifiedSocialCreditCode = item.creditCode
        formData.value.businessType = item.businessType
        formData.value.contactPhone = item.phone
        formData.value.legalRepresentative = item.legalRepresentative
        formData.value.position = item.onsitePosition
        formData.value.partyName = item.partyName
        // 当事人登记页面拆开后这里再赋值
        formData.value.streetOfCompanyAddress = item.streetOfCompanyAddress
        formData.value.address = item.address
      }
    })
  } else {
    formData.value.streetOfCompanyAddress = undefined
    formData.value.address = undefined
    formData.value.postalCode = undefined
    formData.value.unifiedSocialCreditCode = undefined
    formData.value.businessType = undefined
    formData.value.contactPhone = undefined
    formData.value.legalRepresentative = undefined
    formData.value.position = undefined
  }
}
// 当事人搜索以及回显 end =========================================================

// 执法人员搜索以及回显 start =========================================================
const inspectorOptions = ref<Array<any>>([])
const getUserList = async () => {
  const res = await getUserEnforcementNo({})
  if (res.data.length > 0) {
    inspectorOptions.value = res.data.map((item: any) => {
      return { value: item.userId, label: item.name, enforcementNo: item.enforcementNo }
    })
  }
}
getUserList()
// const handlepartySearch2 = async val => {
//   if (val) {
//     await getCodeByUser(val)
//   } else {
//     nextTick(() => {
//       formData.value.inspectorCertNo2 = undefined
//     })
//   }
// }
const handlepartyChange1 = (val: string) => {
  if (val === formData.value.inspectorId2) {
    formData.value.inspectorName1 = ''
    formData.value.inspectorCertNo1 = ''
    formData.value.inspectorId1 = ''
    return
  }
  inspectorOptions.value.forEach(item => {
    if (item.value === val) {
      formData.value.inspectorName1 = item.label
      formData.value.inspectorCertNo1 = item.enforcementNo
    }
  })
}
const handlepartyChange2 = (val: string) => {
  if (val === formData.value.inspectorId1) {
    formData.value.inspectorName2 = ''
    formData.value.inspectorCertNo2 = ''
    formData.value.inspectorId2 = ''
    return
  }
  inspectorOptions.value.forEach(item => {
    if (item.value === val) {
      formData.value.inspectorName2 = item.label
      formData.value.inspectorCertNo2 = item.enforcementNo
    }
  })
}
// 执法人员搜索以及回显 end =========================================================

// const causeArticles = ref<Array<any>>([{ content: '案由测试内容一' }])
const contentArticles = ref<Array<any>>([{ content: '案情简介及立案理由测试内容一' }])
const opinionArticles = ref<Array<any>>([{ content: '承办人意见测试内容一' }])
const remarkArticles = ref<Array<any>>([{ content: '备注测试内容一' }])
// tab补全
const handleSuggestionSelect = (item: any, type?: number) => {
  if (type === 1) {
    // 案由选中
    if (item === undefined) {
      formData.value.caseCauseId = ''
      formData.value.caseCause = ''
      formData.value.caseIntroduction = ''
      return
    }
    formData.value.caseCause = caseCauseList.value.find(i => i.id === item)?.content || ''
    getContent('1', '3', 'caseIntroduction')
  }
}
const caseCauseList = ref<any>([])

const selectCaseCause = (val: string) => {
  formData.value.caseCauseId = val
}

const clearCaseCause = () => {
  formData.value.caseCauseId = ''
  formData.value.caseCause = ''
  formData.value.caseIntroduction = ''
}

const closeCausePicker = () => {
  showCausePicker.value = false
  formData.value.caseCauseId = formData.value.caseCauseId || ''
}

const confirmCaseCause = () => {
  if (formData.value.caseCauseId) {
    handleSuggestionSelect(formData.value.caseCauseId, 1)
  }
  showCausePicker.value = false
}

async function getContent(parentType, type, field) {
  const res = await commontermsGet({
    termType: type,
    pageSize: 9999,
    pageNum: 1,
    status: 0,
    parentId: parentType,
  })
  if (field === 'caseCause') {
    caseCauseList.value = res.data
  } else {
    formData.value[field] = res.data[0].content
  }
}
// 现场检查 start =========================================================
const tableData = ref<any>([])
const checkModalVisible = ref(false)
const checkCurrent = ref('')
const checkList = ref<any>([])
// 获取现场检查列表
const getCheckList = async () => {
  const res: any = await getUnboundSiteInspections({
    pageNum: 1,
    pageSize: 9999,
  })
  checkList.value = res.data.map((item: any) => {
    return { ...item, label: item.record }
  })
}
// 添加现场检查
const handleAdd = () => {
  checkBtnType.value = 'add'
  formData2.value.id = undefined
  checkModalVisible.value = true
}
// 选择现场检查
const handleCheck = async (val: string) => {
  const index = tableData.value.findIndex((item: any) => item.id === val)
  const res = await onSiteInspectionDetail(val)
  if (index === -1) {
    tableData.value.unshift(res.data)
    formData.value.companyProfile = res.data.companyProfile
    formData.value.siteDescription = res.data.siteDescription
    formData.value.inspectorId1 = String(res.data.inspectorId1)
    formData.value.inspectorName1 = res.data.inspectorName1
    formData.value.inspectorCertNo1 = res.data.inspectorCertNo1
    formData.value.inspectorId2 = String(res.data.inspectorId2)
    formData.value.inspectorName2 = res.data.inspectorName2
    formData.value.inspectorCertNo2 = res.data.inspectorCertNo2
  }
}
// 现场检查详情数据
const formData2 = ref<any>({
  field16: undefined, // 是否现场检查 0否 1是
  field21: '0', // 是否上传附件 0否 1是
})

// 编辑现场检查
const checkBtnType = ref('view') // view 查看 edit 编辑
const handleEdit = (row: any, type: string) => {
  checkBtnType.value = type
  const field16 = formData2.value.field16
  const field21 = formData2.value.field21
  formData2.value = { ...row, field16, field21 }
  checkModalVisible.value = true
}
// 删除现场检查
const deleteCase = (index: number) => {
  tableData.value.splice(index, 1)
}
const handleDelete = async (row, index) => {
  try {
    await confirmDeleteSingle(() => deleteCase(index))
  } catch (error) {
    // 用户取消删除
    console.log('用户取消删除案件')
  }
}
// 导出现场检查
const handleExport = async (row: any) => {
  const res = await onSiteInspectionExport([row.id])
  downloadBlob(res)
}

// 保存现场检查
const handleSave = (form: any) => {
  if (form.id && checkBtnType.value !== 'add') {
    const index = tableData.value.findIndex((item: any, index: number) => {
      return item.id === form.id
    })
    tableData.value[index] = form
  } else if (checkBtnType.value === 'edit') {
    tableData.value.unshift({ ...form })
  } else {
    tableData.value.push({ ...form })
  }

  formData.value.companyProfile = tableData.value[0]?.companyProfile
  formData.value.siteDescription = tableData.value[0]?.siteDescription
  formData.value.inspectorId1 = tableData.value[0]?.inspectorId1
  formData.value.inspectorName1 = tableData.value[0]?.inspectorName1
  formData.value.inspectorCertNo1 = tableData.value[0]?.inspectorCertNo1
  formData.value.inspectorId2 = tableData.value[0]?.inspectorId2
  formData.value.inspectorName2 = tableData.value[0]?.inspectorName2
  formData.value.inspectorCertNo2 = tableData.value[0]?.inspectorCertNo2
}

// 现场检查 end =========================================================
const queryRef = ref<any>(null)
const queryRef2 = ref<any>(null)
/** 预览 */
const preViewLoading = ref(false)
const handlePreview = async () => {
  preViewLoading.value = true
  handleSubmit('3')
    .then(async params => {
      const res: any = await registrationcasePreviewPdf(params)
      if (!!res.msg) {
        window.open(res.msg)
      } else {
        ElMessage.warning('预览文件不存在')
      }
      preViewLoading.value = false
    })
    .catch(() => {
      preViewLoading.value = false
    })
}
/** 流转记录按钮操作 */
const circulationList = ref([])
const circulationVisible = ref(false)
async function handleFlowRecord() {
  const res = await getTodoFlowRecord({ instanceId: route.query.procInsId, order: '1' })
  const { data } = res
  circulationList.value = data
  circulationVisible.value = true
}
const formValidate = async () => {
  return new Promise((resolve, reject) => {
    Promise.all([queryRef.value?.validate(), queryRef2.value?.validate()])
      .then(async valid => {
        if (!valid || valid[0] !== true || valid[1] !== true) {
          reject(false)
        } else {
          resolve(true)
        }
      })
      .catch(() => {
        reject(false)
      })
  })
}
const handleSubmit = (status: string) => {
  return new Promise((resolve, reject) => {
    Promise.all([queryRef.value?.validate(), queryRef2.value?.validate()])
      .then(async valid => {
        if (!valid || valid[0] !== true || valid[1] !== true) {
          reject(false)
          return
        }
        const params = {
          ...formData.value,
          siteInspectionRecordIds: tableData.value.map(item => item.id).join(','),
        }
        if (status === '3') {
          // 预览
          resolve(params)
        }
        let saveApi
        if (status === '1') {
          if (route.query.id) {
            saveApi = registrationcaseUpdate
          } else if (status === '1') {
            // 草稿
            saveApi = registrationcaseAdd
          }
        } else if (status === '2') {
          // 提交
          saveApi = registrationcaseSubmit
        }
        await saveApi(params)
        ElMessage.success('保存成功')
        router.back()
      })
      .catch(() => {
        console.log(1)
        reject(false)
      })
  })
}
const handleCacel = () => {
  router.back()
}

// 流程相关 start =========================================================
// 待办页面 提交 / 退回 / 不予立案
const handleSubmitReview = async form => {
  if (route?.query?.type === 'refresh') {
    form.opinion = '同意'
  }
  await registrationcaseReview({
    ...form,
    id: route.query.id,
  })
  proxy.$modal.msgSuccess('操作成功')
  router.back()
}

// 待办页面获取批注列表
const timer = ref(null)
const getAnnotationList = () => {
  return new Promise((resolve, reject) => {
    timer.value = setInterval(() => {
      if (formData.value?.id?.length) {
        clearInterval(timer.value)
        resolve({ ...formData.value })
      } else {
        resolve([])
      }
    }, 500)
  })
}
// 流程相关 end =========================================================

onMounted(() => {
  const { id } = route.query
  if (id) {
    getDetail(id)
  }
  getContent('', '1', 'caseCause')
})

onBeforeMount(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
})

defineExpose({
  handleSubmitReview,
  getAnnotationList,
  formData,
  formValidate,
})
</script>

<style scoped lang="scss"></style>
